public class test06 {
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head==null || head.next==null){
                return head;
            }
            if(k==0){
                return head;
            }
            //连成环
            ListNode tail = head;
            int n = 1;
            while(tail.next!=null){
                tail = tail.next;
                n++;
            }
            tail.next = head;
            //找到应该断的位置
            //newTail的初始值是head，是因为现在要遍历到它距离原来头结点的距离
            ListNode newTail = head;
            ListNode newHead;
            for(int i = 0;i<n-k%n-1;i++){
                newTail = newTail.next;
            }
            newHead = newTail.next;
            newTail.next = null;
            return newHead;
        }
    }
}
